package com.xiaoyu.shenyou.shenyouv1.services.impl;

import cn.hutool.core.util.ObjectUtil;
import com.xiaoyu.shenyou.shenyouv1.common.usertype.UserType;
import com.xiaoyu.shenyou.shenyouv1.entity.CdkUserEntity;
import com.xiaoyu.shenyou.shenyouv1.entity.UserEntity;
import com.xiaoyu.shenyou.shenyouv1.mapper.UserMapper;
import com.xiaoyu.shenyou.shenyouv1.services.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;


@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public boolean survivalCache(int userId) {
        Object user = redisTemplate.opsForValue().get(String.valueOf(userId));
        if (ObjectUtil.isNotNull(user)) {
            //说明存在
            return true;
        }
        return false;
    }

    /**
     * @param userId
     * @return
     */
    @Override
    @Transactional
    public boolean queryUser(int userId) {
        try {
            //数据库中查询
            List<UserEntity> users = userMapper.queryUsers();
            if (selectUser(userId, users)) return true;
            //从卡密库中查询
            CdkUserEntity query = userMapper.query(userId);
            /**
             * 判断卡的类型
             */
            if (ObjectUtil.isNotNull(query)) {
                //不为空，插入用户
                UserEntity user = new UserEntity();
                user.setUser_id(userId).setCreate_time(LocalDateTime.now());
                int type = query.getType();
                if (type == UserType.DAY) {
                    //1天卡
                    user.setType(UserType.DAY);
                }
                if (type == UserType.DAYS) {
                    //3天卡
                    user.setType(UserType.DAYS);
                }
                if (type == UserType.WEEK) {
                    //7天卡
                    user.setType(UserType.WEEK);
                }
                if (type == UserType.DAYS_20) {
                    //20天卡
                    user.setType(UserType.DAYS_20);
                }
                if (type == UserType.MONTH) {
                    //30天卡
                    user.setType(UserType.MONTH);
                }
                userMapper.insertUser(user);
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("类型转换异常：{}，", e.getMessage());
        }
        return false;
    }

    private static boolean selectUser(int userId, List<UserEntity> users) {
        boolean anyMatch = users.stream()
                .distinct()
                .anyMatch(userEntity -> {
                    Duration duration = Duration.between(userEntity.getCreate_time(), LocalDateTime.now());
                    long remainDays = duration.toMinutes() / 60 / 24;
                    /**
                     * 判断卡的类型
                     */
                    Integer type = userEntity.getType();
                    //根据类型取时间
                    int typeDays = UserType.typeGetDays.get(type);
                    return userEntity.getUser_id() == userId && remainDays < typeDays;
                });
        return anyMatch;
    }
}
